//go:build ignore

package main

import (
	"auto/base"
	"auto/check"
	"encoding/json"
	"fmt"
	"math/rand"
	"sync"
	"time"

	"gorm.io/gorm"
)

var db *gorm.DB
var wg sync.WaitGroup
var cfg *check.Cfg

var tables = [...][2]string{
	{"jrk_dp_cyms", "餐饮美食"},
	{"jrk_dp_xxyl", "休闲娱乐"},
	{"jrk_dp_shfw", "生活服务"},
	{"jrk_dp_xxjy", "学校教育"},
	{"jrk_dp_gwgj", "购物逛街"},
	{"jrk_dp_zfjg", "政府机构"},
	{"jrk_dp_ylbj", "医疗保健"},
	{"jrk_dp_yhjr", "银行金融"},
	{"jrk_dp_jdzs", "酒店住宿"},
	{"jrk_dp_fjms", "风景名胜"},
	{"jrk_dp_ggss", "公共设施"},
	{"jrk_dp_swzz", "商务住宅"},
}

func init() {
	var err error
	cfg, err = check.LoadCfg()
	if err != nil {
		fmt.Println("审核配置加载错误", err.Error())
		base.LogWrite(fmt.Sprintf("审核配置加载错误，%v", err.Error()), "check")
		return
	}
	db, err = base.DbConnectLocal()
	if err != nil {
		fmt.Println("数据库连接错误：", err.Error())
		base.LogWrite(fmt.Sprintf("数据库连接错误，%v", err.Error()), "check")
		return
	}
}

func main() {
	fmt.Println("进程已启动")
	base.LogWrite("进程已启动", "check")
	for i := 0; i < len(tables); i++ {
		wg.Add(1)
		go run(i)
	}
	wg.Wait()
	base.LogWrite("进程已退出", "check")
	fmt.Println("进程已退出")
}

func run(index int) {
	time.Sleep(time.Duration(index) * time.Second)
	fmt.Println("启动：" + tables[index][1])

	logName := "check_" + tables[index][1]
	base.LogWrite(fmt.Sprintf("模型：%v，info：开始任务", tables[index][1]), logName)

	startStamp := getTimestamp(fmt.Sprintf("%v %v:00", time.Now().Format("2006-01-02"), cfg.Starttime))
	endStamp := getTimestamp(fmt.Sprintf("%v %v:00", time.Now().Format("2006-01-02"), cfg.Endtime))
	count := 0

	for {
		if time.Now().Unix() < startStamp || time.Now().Unix() > endStamp {
			base.LogWrite(fmt.Sprintf("模型：%v，info：已过放出时间", tables[index][1]), logName)
			fmt.Println("模型："+tables[index][1], "info：已过放出时间")
			break
		}
		if count >= cfg.Count {
			base.LogWrite(fmt.Sprintf("模型：%v，info：已达今日放出上限", tables[index][1]), logName)
			fmt.Println("模型："+tables[index][1], "info：已达今日放出上限")
			break
		}
		dianpu := base.LocalDianpu{}
		result := db.Table(tables[index][0]).Where("is_show = 0").Take(&dianpu)
		if result.RowsAffected != 1 {
			base.LogWrite(fmt.Sprintf("模型：%v，info：没有数据", tables[index][1]), logName)
			fmt.Println("模型："+tables[index][1], "info：没有数据")
			break
		}
		var affected int64 = 0
		if dianpu.Is_make == 1 {
			affected = updateShow(&dianpu, index)
		} else {
			affected = updateMake(&dianpu, index)
		}
		count++
		if affected != 1 {
			base.LogWrite(fmt.Sprintf("模型：%v，城市：%v，名称：%v，ID：%v，info：执行放出失败！", tables[index][1], dianpu.Cityname, dianpu.Name, dianpu.Id), logName)
		} else {
			base.LogWrite(fmt.Sprintf("模型：%v，城市：%v，名称：%v，ID：%v，info：放出成功", tables[index][1], dianpu.Cityname, dianpu.Name, dianpu.Id), logName)
		}
		time.Sleep(time.Duration(randInt(cfg.Sleep_s, cfg.Sleep_b)) * time.Second)
	}

	base.LogWrite(fmt.Sprintf("模型：%v，info：任务已结束", tables[index][1]), logName)
	fmt.Println("退出：" + tables[index][1])
	wg.Done()
}

func updateShow(dianpu *base.LocalDianpu, index int) int64 {
	result := db.Table(tables[index][0]).Where("id = ?", dianpu.Id).Updates(map[string]interface{}{"is_show": 1, "show_time": time.Now().Unix()})
	return result.RowsAffected
}

func updateMake(dianpu *base.LocalDianpu, index int) int64 {
	litpic := ""
	if dianpu.Photos != "" {
		temp := make([]interface{}, 3)
		json.Unmarshal([]byte(dianpu.Photos), &temp)
		url := temp[0].(map[string]interface{})["url"].(string)
		litpic, _ = check.GetPic(url, dianpu.Uid)
	}
	first := check.GetChineseFirstLetter(dianpu.Name)
	gongjiao := check.GetAround(dianpu.Location, "公交")
	ditie := check.GetAround(dianpu.Location, "地铁")
	tingche := check.GetAround(dianpu.Location, "停车场")
	canting := check.GetAround(dianpu.Location, "餐厅")
	jiudian := check.GetAround(dianpu.Location, "酒店")
	jieshao := check.GetJieshao(dianpu.Location, dianpu.Name, dianpu.Address)
	result := db.Table(tables[index][0]).Where("id = ?", dianpu.Id).Updates(map[string]interface{}{"first": first, "gongjiao": gongjiao, "ditie": ditie, "tingche": tingche, "canting": canting, "jiudian": jiudian, "jieshao": jieshao, "is_make": 1, "is_show": 1, "update_time": time.Now().Unix(), "show_time": time.Now().Unix(), "litpic": litpic})
	return result.RowsAffected
}

func randInt(min, max int) int {
	rand.Seed(time.Now().Unix()) //随机种子
	return rand.Intn(max-min) + min
}

func getTimestamp(datetime string) int64 {
	timeLayout := "2006-01-02 15:04:05"
	loc, _ := time.LoadLocation("Local") //获取时区
	tmp, _ := time.ParseInLocation(timeLayout, datetime, loc)
	timestamp := tmp.Unix()
	return timestamp
}
